package top.eggcode.security.aspect;

import org.apache.commons.lang3.StringUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.core.Ordered;
import org.springframework.stereotype.Component;
import top.eggcode.common.exception.ApplicationException;
import top.eggcode.common.exception.InnerAuthException;
import top.eggcode.spring.HttpServletUtil;
import top.eggcode.security.anno.InnerAuth;

@Aspect
@Component
public class InnerAuthHandler implements Ordered {

    @Around("@annotation(innerAuth)")
    public Object innerAround(ProceedingJoinPoint point, InnerAuth innerAuth) throws Throwable
    {
        String source = HttpServletUtil.getRequest().getHeader("source");
        // 内部请求验证
        if (!StringUtils.equals("inner", source))
        {
            throw new ApplicationException("没有内部访问权限");
        }

        String userid = HttpServletUtil.getRequest().getHeader("user_id");
        String username = HttpServletUtil.getRequest().getHeader("username");
        // 用户信息验证
        if (!innerAuth.value() && (StringUtils.isEmpty(userid) || StringUtils.isEmpty(username)))
        {
            throw new InnerAuthException("没有设置用户信息");
        }
        return point.proceed();
    }

    @Override
    public int getOrder() {
        return Ordered.HIGHEST_PRECEDENCE + 1;
    }
}
